/**
 * requestProxy.js
 * 封装fetch复杂操作的对象
 *
 * created by qiuwei
 * 2016年03月28日
 */

import fetch from 'isomorphic-fetch';
import { REPLY_DATA } from '../constants/replyData';
import { HTTP_RESULT } from '../constants/protocol';

function showData(data, url) {
	console.log('>>>>> 响应数据 <<<<<');
	console.log(JSON.stringify(data));
	console.log(`请求地址:${url}`);
}

export default {
	post: async function(url, body) {
		if (global.DEBUG) {
			console.log('>>>>> POST 请求数据 <<<<<');
			console.log(JSON.stringify(body));
			console.log(`请求地址:${url}`);
		}
		
		let response = await fetch(url, {
			method: 'post',
			headers: {
				'Accept': 'application/json',
				'Content-Type': 'application/json'
			},
			body: JSON.stringify(body)
		});

		return await response.json().then((data) => {
			
			if (global.DEBUG) {
				showData(data, url);
				data.request = JSON.stringify(body);
				data.response = JSON.stringify(data);
			}

			return data;
		});
	},
	get: async function(url) {
		// if (global.DEBUG) {
		// 	console.log('>>>>> GET 请求数据 <<<<<');
		// 	console.log(`请求地址:${url}`);
		// }

		let response = await fetch(url);
		
		// if (response.status === 200) {
		// 	return await response.json();
		// } else {
		// 	return await response.text();
		// }
		return await response.json().then((data) => {
			if (global.DEBUG) {
				// showData(data, url);
				data.request = JSON.stringify(body);
				data.response = JSON.stringify(data);
			}

			return data;
		});
	}
}